<?php
/**
 * Description of c_site_mailer_controller
 *
 * @author tonatos
 */
class c_site_mailer_controller extends c_base_controller{

    protected function cron(){
        global $modx;

        //cобираем данные со всем модулей
        $forum = new c_forum_controller();
        $for_forum = $forum->call_protected("cron");

        $for_doc = $this->my_cron();

        //Нет данных
        if (($for_forum===false)&&($for_doc===false)) return;

        //Получаем список пользователей (заранее отметая не одписанных)
        $users = $modx->db->get_records("web_user_attributes","blocked=0 and subscribes!='' and id!=-1 and activated!=0","id");

        $this->subscribe_link = $modx->config['site_url']."cabinet/subscribe.html";

        $i=1;
        foreach ($users as $user){

            //Определяем что отправлять
            $subscribes = explode(",",$user->subscribes);

            $this->for_forum = (in_array("forum",$subscribes))?$for_forum:false;
            $this->for_doc = (in_array("site",$subscribes))?$for_doc:false;

            if ((!$this->for_forum)&&(!$this->for_doc)){
                continue;
            }

            //Формируем письмо
            $this->fullname = $user->fullname;
            $mail = $this->show("cron_mail",true);

            echo ($i++)." $user->email [$user->subscribes] ";

            if (!$this->send_mail($user->email, "Новое на сайте", $mail)){
                echo " - error!";
            }
            echo "\n";
        }

    }

    private function my_cron($debug=false){
        global $modx;
        $raws = $modx->db->get_records("select r.id as raw_id, d.id, d.published, d.deleted from ".$modx->getFullTableName("site_mailer_raw")." r, ".
                $modx->getFullTableName("site_content")." d where d.id=r.param_id and r.controller='' order by r.createdon");


        $doc_ids = array();
        $raws_id = array();

        foreach($raws as $row){
            if (($row->published==1)&&($row->deleted==0)){
                $doc_ids[$row->id] = $row->id;
                $raws_ids[] = $row->id_raw;
            }
        }

        if (empty($doc_ids)) return false;

        $docs=array();
        foreach ($doc_ids as $id) {
            $doc = new Document($id);

            $img = $doc->GetTV("img");
            if (!empty($img)){
                try {
                    $thumb = PhpThumbFactory::create(MODX_BASE_PATH.$img);
                    $filename = "cron_$id.jpg";
                    //Подгатавливаем путь для сохранения
                    $path = "assets/images/cron_tn/";
                    if (!file_exists(MODX_BASE_PATH.$path)){
                        mkdir(MODX_BASE_PATH.$path);
                    }

                    $thumb->adaptiveResizeQuadrant(160,120);
                    $thumb->save(MODX_BASE_PATH.$path.$filename,"JPG");

                    $doc->cron_img = $modx->config['site_url'].$path.$filename;

                }catch (Exception $e){
                    
                }

            }


            $docs[] = $doc;
        }

        $this->docs= $docs;

        $ids = implode(",",$doc_ids);
        if ($debug==false){
            $modx->db->delete($modx->getFullTableName("site_mailer_raw"),"controller='' and param_id in ($ids)");
        }

        return $this->show("cron",true);
        
    }

    public function send_mail($mailto, $subject, $body) {
        global $modx;
        require_once MODX_BASE_PATH.'manager/includes/controls/class.phpmailer-lite.php';

        $emailsender = $modx->config['emailsender'];
        $site_name = $modx->config['site_name'];
        $site_start = $modx->config['site_start'];

        // составление письма
        $smail = new PHPMailerLite();
        $smail->IsMail();
        $smail->IsHTML(true);
        $smail->AddCustomHeader("Precedence: bulk");

        $smail->From = $emailsender;
        $smail->FromName = $site_name;
        $smail->Subject = $subject;
        $smail->Body = $body;
        $smail->AddAddress($mailto);
        return $smail->Send();
    }

    public function test_mail(){
        global $modx;

        $this->subscribe_link = $modx->config['site_url']."cabinet/subscribe.html";
        $this->for_forum = false;
        $this->for_doc = $this->my_cron(true);

        $this->fullname = "Администратор сайта";
        $mail = $this->show("cron_mail",true);

        if (!$this->send_mail($modx->config['emailsender'], "Новое на сайте", $mail)){
            echo " - error!";
        }

        echo "Тестовое письмо отправлено ".time();
    }

}
?>
